package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.cache.service.IQuestionStatisRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.QuestionStatisVO;
import cn.wolfcode.luowowo.comment.domain.WendaComment;
import cn.wolfcode.luowowo.comment.query.WendaCommentQuery;
import cn.wolfcode.luowowo.comment.service.IWendaCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.community.domain.Answer;
import cn.wolfcode.luowowo.community.domain.Question;
import cn.wolfcode.luowowo.community.query.QuestionQuery;
import cn.wolfcode.luowowo.community.service.IAnswerService;
import cn.wolfcode.luowowo.community.service.IQuestionService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.search.query.IndexSearchQuery;
import cn.wolfcode.luowowo.search.service.IQuestionSearchService;
import cn.wolfcode.luowowo.search.template.QuestionTemplate;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import cn.wolfcode.luowowo.website.util.UploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("community")
public class CommunityController {

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IQuestionService questionService;

    @Reference
    private IAnswerService answerService;

    @Reference
    private IWendaCommentService wendaCommentService;

    @Reference
    private IQuestionSearchService questionSearchService;

    @Reference
    private IQuestionStatisRedisService questionStatisRedisService;


    @Value("${file.path}")
    private String filePath;


    @RequestMapping("")
    public String index(Model model, @ModelAttribute("qo")QuestionQuery qo,@UserParam UserInfo userInfo){

        PageInfo pageInfo = questionService.query(qo);
        List<WendaComment> tcs = wendaCommentService.selectForTop10();
        PageInfo page=questionService.queryForNum(qo);
        model.addAttribute("tcs", tcs);
        model.addAttribute("page",page);
        model.addAttribute("userinfo",userInfo);
        model.addAttribute("pageInfo",pageInfo);
        return "community/wenda";
    }

    @RequestMapping("/q")
    public String q(Model model, @ModelAttribute("qo") IndexSearchQuery qo) {
        AggregatedPage<QuestionTemplate> questions = questionSearchService.selectByKeyword(qo, "title");
        List<WendaComment> tcs = wendaCommentService.selectForTop10();
        QuestionQuery query = new QuestionQuery();
        PageInfo page=questionService.queryForNum(query);
        model.addAttribute("page",page);
        model.addAttribute("tcs", tcs);
        model.addAttribute("questions", questions);
        return "index/searchwenda";
    }


    @RequestMapping("/input")
    public String input(Model model){
        List<Destination> dests = destinationService.selectAll();
        model.addAttribute("dests",dests);
        return "community/input";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(Question question, @UserParam UserInfo userInfo){
        question.setUserInfo(userInfo);
        questionService.saveOrUpdate(question);
        return new AjaxResult();
    }

    @RequestMapping("/commentAdd")
    @ResponseBody
    public Object commentAdd(String id, String content, @UserParam UserInfo userInfo) {
        if (userInfo == null) {
            return new AjaxResult(false,"请登陆后操作!!");
        }
        WendaComment wendaComment = wendaCommentService.commentAdd(id, content, userInfo);
        //questionService.updateNum(Long.valueOf(id));
       /* try {
            questionStatisRedisService.addStaticNum(Long.valueOf(id),1, QuestionStatisVO.QUESTION_STATISVO_THUMBSUPNUM);
        } catch (Exception e){
            throw  new RuntimeException("评论失败");
        }*/

        return new AjaxResult().addData(wendaComment);
    }


    @RequestMapping("detail")
    public String detail(Model model,Long id){
        //查询问题下的所有回答
        List<Answer> list=answerService.selectForList(id);
        //把当前问题下的所有回答封装在question下的answer集合中
        Question question=questionService.selectQuestionById(id);
        model.addAttribute("question",question);
        model.addAttribute("lists",list);
        //list
        WendaCommentQuery qo = new WendaCommentQuery();
        qo.setAnswerId(id);
        qo.setPageSize(Integer.MAX_VALUE);
        Page<WendaComment> page = wendaCommentService.query(qo);
        model.addAttribute("list",page.getContent());
        return "community/detail";
    }

    @RequestMapping("/answer")
    @ResponseBody
    public Object answer(WendaComment content, @UserParam UserInfo userInfo){
        if(userInfo==null){
            return new AjaxResult(false,"请登陆后操作!!");
        }
        Question question = questionService.get(content.getAnswerId());
        content.setQuestionTitle(question.getTitle());
        content.setUserId(userInfo.getId());
        content.setLevel(userInfo.getLevel());
        content.setHeadImgUrl(userInfo.getHeadImgUrl());
        content.setUsername(userInfo.getNickname());
        wendaCommentService.save(content);
        questionService.updateNum(content.getAnswerId());
        return new AjaxResult().addData(wendaCommentService.get(content.getAnswerId()).getContent());
    }


    @RequestMapping("/questionThumbup")
    @ResponseBody
    public AjaxResult questionThumbup(Long tid,@UserParam UserInfo userInfo) {
        //首先我们调用顶的方法
        //先进行登录判断
        if(userInfo==null){
            return new AjaxResult(false,"请先进行登录喔",null,102);
        }
        //如果有登录那么调用方法
        try {
            boolean result=questionStatisRedisService.isQuestionThumbup(tid,userInfo.getId());
            if (result){
                questionStatisRedisService.addSortNum(RedisKeys.QUESTION_STATIC_VO.getPrefix(),tid,1);
            }
            QuestionStatisVO vo=questionStatisRedisService.getVoByQuestionId(tid);
            return new AjaxResult(result,"",vo);
        }  catch (Exception e) {
            throw new RuntimeException("收藏失败");
        }
    }




    @RequestMapping("coverImageUpload")
    @ResponseBody
    public String coverImageUpload(MultipartFile pic) {
        String fileName = UploadUtil.upload(pic, filePath);
        return fileName;
    }

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception {
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif", ".png", ".jpg", ".jpeg", ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\"" + up.getFileName() + "\", \"originalName\": \"" + up.getOriginalName() + "\", \"size\": " + up.getSize()
                + ", \"state\": \"" + up.getState() + "\", \"type\": \"" + up.getType() + "\", \"url\": \"" + up.getUrl() + "\"}";
        result = result.replaceAll("\\\\", "\\\\");
        if (callback == null) {
            return result;
        } else {
            return "<script>" + callback + "(" + result + ")</script>";
        }
    }


}

